import React from 'react';
import Footer from './components/Footer';
import Header from './components/Header';
import List from './components/List';
import './App.css';

class App extends React.Component {
	// 列表
	state = {
		todoList: [
			{id: '001', doName: '写代码', done: true},
			{id: '002', doName: '运动', done: true},
			{id: '003', doName: '打游戏', done: false},
		],
	};

	// 添加数据
	addTodo = obj => {
		this.setState({todoList: [obj, ...this.state.todoList]});
	};

	// 修改数据勾选状态
	updateTodo = (id, done) => {
		const {todoList} = this.state;
		// 查找并且修改数据
		const newList = todoList.map(item => {
			if (item.id === id) {
				// 返回修改后的对象
				return {...item, done: done};
			} else {
				return item;
			}
		});
		// 重置数据列表
		this.setState({todoList: newList});
	};

	// 删除单一数据
	deleteOneTodo = id => {
		const {todoList} = this.state;
		const newList = todoList.filter(item => {
			return item.id !== id;
		});
		// 重置数据列表
		this.setState({todoList: newList});
	};

	// 全部反选
	checkedAll = flag => {
		const {todoList} = this.state;
		// 全选
		if (flag) {
			const newList = todoList.map(item => {
				return {...item, done: true};
			});
			this.setState({todoList: newList});
		} else {
			// 全不选
			const newList = todoList.map(item => {
				return {...item, done: false};
			});
			this.setState({todoList: newList});
		}
	};

	// 清除所有已选
	deleteAllChecked = () => {
		const {todoList} = this.state;
		const newList = todoList.filter(item => {
			return !item.done;
		});
		this.setState({todoList: newList});
	};

	render() {
		return (
			<div className="todo-container">
				<div className="todo-wrap">
					<Header addTodo={this.addTodo} />
					<List
						todoList={this.state.todoList}
						updateTodo={this.updateTodo}
						deleteOneTodo={this.deleteOneTodo}
					/>
					<Footer
						todoList={this.state.todoList}
						checkedAll={this.checkedAll}
						deleteAllChecked={this.deleteAllChecked}
					/>
				</div>
			</div>
		);
	}
}

export default App;
